package router

import (
	"crypto/md5"
	"fmt"
	"reflect"
	"strconv"
	"time"

	"../mode"
	"github.com/tungyao/spruce"
)

type Login struct {
	Pub  string
	Name string
	Uid  string
}

// 通道监测文章的变化
var Se *spruce.Hash
var Monitor chan int

func init() {
	Se = spruce.CreateHash(4096)
	Monitor = make(chan int, 100)
	go func() {
		for v := range Monitor {
			row := D.QueryRow("select a.id,a.uid,a.author,a.title,a.origin_body,a.create_time,a.update_time,b.name as category from articles a left join category b on a.category=b.id where a.is_delete=0 and a.id=?", v)
			st := mode.Articles{}
			row.Scan(&st.Id, &st.Uid, &st.Author, &st.Title, &st.Body, &st.Create_time, &st.Update_time, &st.Category)
			P.Set([]byte("we_"+strconv.Itoa(st.Id)), mode.ArticleData{
				Data:    []mode.Articles{st},
				Page:    6,
				Current: 1,
			}, 0)
			fmt.Println("重新存储了", st.Id)
		}
	}()
}
func GetSession(key []byte) []byte {
	a := md5.New()
	a.Write(key)
	return Se.Get(a.Sum(nil)).([]byte)
}
func SetSession(key []byte, value []byte) {
	a := md5.New()
	a.Write(key)
	Se.Set(a.Sum(nil), value, 3600)
}
func IsZero(a interface{}) bool {
	t := reflect.TypeOf(a).Elem()
	v := reflect.ValueOf(a).Elem()
	for i := 0; i < t.NumField(); i++ {
		if v.Field(i).IsZero() {
			return false
		}
	}
	return true
}
func NewToken(s []byte) []byte {
	a := md5.New()
	a.Write(s)
	return []byte(fmt.Sprintf("%x", a.Sum([]byte(time.Now().String()))))
}
